<template>
  <div class="common-layout">
    <el-container>
      <el-aside width="200px" style="min-height: 100vh; background-color: rgb(22,46,86)">
        <div class="aside-head-info"
             style="width: 200px; height: 80px; align-items: center; justify-items: center; display: flex">
          <span
              style="color: #f9f9f9; display: flex; align-items: center; justify-content: center; width: 200px">欢迎您，系统管理员</span>
        </div>
        <el-menu style="border: none" :default-active="currentUrl" router background-color="#162E56"
                 text-color="#f9f9f9">
          <el-menu-item index="/top-manager/index">
            <template #title>
              <el-icon>
                <User/>
              </el-icon>
              用户首页
            </template>
          </el-menu-item>
          <el-menu-item index="/top-manager/account-manage">
            <template #title>
              <el-icon>
                <Edit/>
              </el-icon>
              账户管理
            </template>
          </el-menu-item>
          <el-menu-item index="/top-manager/auth-distribute">
            <template #title>
              <el-icon>
                <Lock/>
              </el-icon>
              权限分配
            </template>
          </el-menu-item>
          <el-menu-item index="/top-manager/manage-restaurant">
            <template #title>
              <el-icon>
                <DishDot/>
              </el-icon>
              食堂管理
            </template>
          </el-menu-item>
          <el-menu-item index="/top-manager/remark-control">
            <template #title>
              <el-icon>
                <ChatDotSquare/>
              </el-icon>
              评论管理
            </template>
          </el-menu-item>
          <el-menu-item index="/top-manager/community-surveillance">
            <template #title>
              <el-icon>
                <Camera/>
              </el-icon>
              社区管理
            </template>
          </el-menu-item>
        </el-menu>
      </el-aside>
      <el-container>
        <el-header
            style="box-shadow: 2px 0 6px rgba(0, 21, 41, .36); display: flex; align-items: center; justify-content: space-between">
          <el-breadcrumb :separator-icon="ArrowRight">
            <el-breadcrumb-item v-for="item in route.matched" :to="{path: item.path}">{{ item.meta.title }}
            </el-breadcrumb-item>

          </el-breadcrumb>
          <div class="avatar-container" style="align-items: center; display: flex; justify-content: flex-end">
            <el-dropdown style="display: flex; align-items: center; justify-content: flex-end" placement="bottom">
        <span class="el-dropdown-link"
              style="display: flex; align-items: center;">
          <el-avatar :size="24" :src="avatarSrc" style="margin: 0 5px"/>
          {{ '欢迎您，' + nickname }}
        </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item>个人中心</el-dropdown-item>
                  <el-dropdown-item>退出登录</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </el-header>
        <el-main>
          <div class="app-container">
            <!--            查询表单-->
            <el-form :model="queryParams" ref="queryForm" size="default" :inline="true" label-width="68px">
              <el-form-item label="用户账号" prop="userName">
                <el-input
                    v-model="queryParams.userName"
                    placeholder="请输入用户账号"
                    clearable
                    @keyup.enter.native="handleQuery"
                />
              </el-form-item>
              <el-form-item label="用户昵称" prop="nickName">
                <el-input
                    v-model="queryParams.nickName"
                    placeholder="请输入用户昵称"
                    clearable
                    @keyup.enter.native="handleQuery"
                />
              </el-form-item>
              <el-form-item label="用户角色" prop="userType">
                <el-select v-model="queryParams.userType" placeholder="请选择用户角色" clearable>
                  <el-option
                      v-for="item in dict_user_type"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="账户状态" prop="status">
                <el-select v-model="queryParams.status" placeholder="请选择账户状态" clearable>
                  <el-option
                      v-for="item in dict_status"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                  />
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" :icon="Search" size="default" @click="handleQuery">搜索</el-button>
                <el-button :icon="Refresh" size="default" @click="resetQuery">重置</el-button>
              </el-form-item>
            </el-form>
            <!--            功能按键-->
            <el-row :gutter="10" class="mb8">
              <el-col :span="1.5">
                <el-button
                    type="primary"
                    plain
                    :icon="Plus"
                    size="small"
                    @click="handleAdd"
                >新增
                </el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button
                    type="success"
                    plain
                    :icon="Edit"
                    size="small"
                    :disabled="single"
                    @click="handleUpdate"
                >修改
                </el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button
                    type="danger"
                    plain
                    :icon="Delete"
                    size="small"
                    :disabled="multiple"
                    @click="handleDelete"
                >删除
                </el-button>
              </el-col>
            </el-row>
            <!--            主体数据表格-->
            <el-table v-loading="tableLoading" :data="tableData" @selection-change="handleSelectionChange">
              <el-table-column type="selection" width="55" align="center"/>
              <el-table-column label="id" align="center" prop="userId" v-if="false"/>
              <el-table-column label="用户账号" align="center" prop="userName"/>
              <el-table-column label="用户头像" align="center">
                <template #default="scope">
                  <img :src="baseStaticRecourseAPI[NOW_ENVIRONMENT]+scope.row.avatar" style="width: 50px; height: 50px"
                       alt="暂无用户头像"/>
                </template>
              </el-table-column>
              <el-table-column label="用户昵称" align="center" prop="nickName"/>
              <el-table-column label="用户角色" align="center" prop="userType"/>
              <el-table-column label="用户电话" align="center" prop="phonenumber"/>
              <el-table-column label="账户状态" align="center">
                <template #default="scope">
                  <el-button :type="scope.row.status==='正常'?'primary':'danger'" size="small"
                             @click="changeAccountStatus(scope.row)">{{ scope.row.status }}
                  </el-button>
                </template>
              </el-table-column>
              <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template #default="scope">
                  <el-button
                      size="small"
                      link
                      :icon="Edit"
                      @click="handleUpdate(scope.row)"
                  >修改
                  </el-button>
                  <el-button
                      size="small"
                      link
                      :icon="Delete"
                      @click="handleDelete(scope.row)"
                  >删除
                  </el-button>
                  <el-button size="small" link :icon="More" @click="handleViewMoreInfo(scope.row)">更多</el-button>
                </template>
              </el-table-column>
            </el-table>

            <!--            分页查询组件-->
            <el-pagination
                v-show="total>0"
                :total="total"
                @change="handlePageSelectChange"/>
            <!--新增/修改对话框-->
            <el-dialog v-model="dialogVis" width="400px" append-to-body @close="cancelForm">
              <template #header>
                <span>{{ dialogTitle }}</span>
              </template>
              <el-form :model="form" style="align-items: center" :rules="formRules" ref="ruleFormRef">
                <el-form-item label="用户账号" prop="userName">
                  <el-input v-model="form.userName" placeholder="请输入用户账号" clearable/>
                </el-form-item>
                <!--:on-preview="handlePictureCardPreview"↓↓-->
                <el-form-item label="用户头像">
                  <el-upload
                      v-model:file-list="fileList"
                      ref="upload"
                      list-type="picture-card"
                      :on-remove="handleRemove"
                      :auto-upload="false"
                      :limit="1"
                      :on-exceed="handleExceed"
                      :on-change="handleSelectedImgChange">
                    <template #tip>
                      限制上传一张图片，超出将被自动替换
                    </template>
                    <el-icon>
                      <Plus/>
                    </el-icon>
                  </el-upload>
                </el-form-item>
                <el-form-item label="用户昵称" prop="nickName">
                  <el-input v-model="form.nickName" placeholder="请输入用户昵称" clearable/>
                </el-form-item>
                <el-form-item label="用户角色" prop="userType">
                  <el-select v-model="form.userType" placeholder="请选择用户角色" clearable>
                    <el-option
                        v-for="item in dict_user_type"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                    />
                  </el-select>
                </el-form-item>
                <el-form-item label="用户密码" prop="password">
                  <el-input type="password" v-model="form.password"
                            :placeholder="dialogTitle==='新增用户'?'请输入用户密码':'请输入用户新密码'" clearable/>
                </el-form-item>
                <el-form-item label="用户性别" prop="sex">
                  <el-select v-model="form.sex" placeholder="请选择用户性别" clearable>
                    <el-option
                        v-for="item in dict_gender"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                    />
                  </el-select>
                </el-form-item>
                <el-form-item label="用户手机" prop="phonenumber">
                  <el-input v-model="form.phonenumber" placeholder="请输入用户手机" clearable/>
                </el-form-item>
                <el-form-item label="用户手机" prop="email">
                  <el-input v-model="form.email" placeholder="请输入用户邮箱" clearable/>
                </el-form-item>
                <el-form-item label="账户状态" prop="status">
                  <el-select v-model="form.status" placeholder="请选择用户状态" clearable>
                    <el-option
                        v-for="item in dict_status"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                    />
                  </el-select>
                </el-form-item>
                <el-form-item>
                  <el-button @click="submitForm(ruleFormRef)" type="primary">确认</el-button>
                  <el-button @click="cancelForm" type="primary">取消</el-button>
                </el-form-item>
              </el-form>
            </el-dialog>

            <el-dialog v-model="moreDialogVis" width="400px" append-to-body @close="cancelMore">
              <template #header>
                <span>更多信息</span>
              </template>
              <p>用户性别：{{ form.sex }}</p>
              <p>用户邮箱：{{ form.email }}</p>
            </el-dialog>
          </div>
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>

<script setup>
import {useRoute} from "vue-router";
import {ArrowRight, Delete, Edit, More, Plus, Refresh, Search} from "@element-plus/icons-vue";
import {
  dict_gender,
  dict_status,
  dict_user_type,
  emptyValidator,
  generalEmailValidator,
  generalPasswordValidator,
  generalPhoneNumberValidator,
  generalValidatorJudgeIfEmpty
} from "../../utils/common.js";
import {
  addUser,
  deleteUsers,
  queryAllSatisfiedUsers,
  queryDetailUser,
  updateUser
} from "../../web-api/system-manager/account-manage.js";
import {ElMessage, ElMessageBox, genFileId} from "element-plus";
import {baseStaticRecourseAPI, NOW_ENVIRONMENT} from "../../baseAPIConfig.js";
import {getLocalStorage, KEY_AVATAR, KEY_NICKNAME} from "../../utils/localStorge.js";

let route = useRoute();

const handlePageSelectChange = (newPageNum, newPageSize) => {
  console.log(newPageNum, newPageSize)
  queryParams.pageSize = newPageSize;
  queryParams.pageNum = newPageNum;
  getList(queryParams);
}

// 控制更多信息对话框的可见性
let moreDialogVis = ref(false);

// 取消
const cancelMore = () => {
  moreDialogVis.value = false;
  generalFormReset();
}

// 上传文件列表，修改时请求下后端
let fileList = ref([{
  name: 'test.png',
  url: 'https://i.b2b168.com/wrzimg.jpg'
}])

// 点击删除图片时触发
const handleRemove = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles)
}

// 上传内容更改时触发
const handleSelectedImgChange = (ev) => {
  avatarContent.fileContent = ev.raw;
}

// 上传引用
let upload = ref()

// 超出上传限制时调用
const handleExceed = (files) => {
  upload.value.clearFiles()
  const file = files[0]
  file.uid = genFileId()
  upload.value.handleStart(file)
}

// 提交表单
const submitForm = (rule) => {
  rule.validate(valid => {
    if (valid) {
      let formData = new FormData()
      formData.append("user", new Blob([JSON.stringify(form)], {
        type: "application/json"
      }));
      formData.append("avatar", avatarContent.fileContent);
      if (form.userId === null || form.userId === '') {
        addUser(formData).then(res => {
          ElMessage.success("新增成功！")
          dialogVis.value = false;
          getList(queryParams);
        })
      } else {
        updateUser(formData).then(res => {
          ElMessage.success("修改成功！");
          dialogVis.value = false;
          getList(queryParams);
        })
      }
      generalFormReset();
      resetAvatarContent();
    }
  })
}

// 表单引用
let ruleFormRef = ref()
// 表单验证规则
const formRules = ref({
  userName: [{validator: generalValidatorJudgeIfEmpty("用户账号不能为空！"), trigger: 'blur'}],
  nickname: [{validator: generalValidatorJudgeIfEmpty("用户昵称不能为空！"), trigger: 'blur'}],
  userType: [{validator: generalValidatorJudgeIfEmpty("用户角色不能为空！"), trigger: 'blur'}],
  password: [{validator: generalPasswordValidator("用户密码"), trigger: 'blur'}],
  status: [{validator: emptyValidator(), trigger: 'blur'}],
  email: [{validator: generalEmailValidator("用户邮箱"), trigger: 'blur'}],
  phonenumber: [{validator: generalPhoneNumberValidator("用户手机"), trigger: 'blur'}],
  sex: [{validator: emptyValidator(), trigger: 'blur'}]
})

// 对话框取消按钮
const cancelForm = () => {
  dialogVis.value = false;
  generalFormReset();
}

// 查看更多信息
const handleViewMoreInfo = (row) => {
  queryDetailUser(row.userId).then(response => {
    form.userId = response.data.userId;
    form.userName = response.data.userName;
    form.nickName = response.data.nickName;
    form.userType = response.data.userType
    form.sex = response.data.sex === "0" ? "男" : (response.data.sex === "1" ? "女" : "未知")
    form.status = response.data.status;
    form.email = response.data.email;
    form.phonenumber = response.data.phonenumber;
  })
  moreDialogVis.value = true;
}

// 表格中选中数据列的id
let ids = ref([])

// 表格选择列发生变化时触发
const handleSelectionChange = (selected) => {
  ids.value = selected.map(item => item.userId);
  single.value = selected.length !== 1;
  multiple.value = !selected.length;
}

// 单独的一个按钮用于切换用户账户状态
const changeAccountStatus = (row) => {
  generalFormReset();
  ElMessageBox.confirm(`是否改变账号为${row.userName}的用户的账户状态？`, "提示", {
    cancelButtonText: '取消',
    confirmButtonText: '确定',
    type: "warning"
  }).then(() => {
    form.status = row.status === '正常' ? '1' : '0';
    updateUser(form).then(res => {
      ElMessage.success("修改成功！");
      getList(queryParams);
    }).catch(err => console.log(err))
  }).catch(() => {
    ElMessage.info("状态更改取消")
  })
}

// 选择为一个都时候为false
let single = ref(true)
// 选择为0个的时候为true
let multiple = ref(true)
// 对话框标题
let dialogTitle = ref('修改')
// 对话框可见性
let dialogVis = ref(false)

// 表单重置
const generalFormReset = () => {
  if (!ruleFormRef.value) {
    return;
  }
  ruleFormRef.value.resetFields()
}

const handleAdd = () => {
  dialogTitle.value = "新增用户";
  resetAvatarContent();
  generalFormReset();
  dialogVis.value = true;
}

const handleUpdate = (row) => {
  queryDetailUser(row.userId).then(response => {
    fileList.value[0].url = response.data.avatar;
    fileList.value[0].name = response.data.avatar.split("/").slice(-1)[0]
    form.userId = response.data.userId;
    form.userName = response.data.userName;
    form.nickName = response.data.nickName;
    form.userType = response.data.userType
    form.sex = response.data.sex
    form.status = response.data.status;
    form.email = response.data.email;
    form.phonenumber = response.data.phonenumber;
  })
  dialogTitle.value = "更改用户信息";
  resetAvatarContent();
  generalFormReset();
  dialogVis.value = true;
}

const handleDelete = (row) => {
  let id = row.userId || ids.value;
  ElMessageBox.confirm(`是否删除这些账户？`, "警告", {
    cancelButtonText: '取消',
    confirmButtonText: '确定',
    type: "warning"
  }).then(() => {
    deleteUsers(id).then(res => {
      if (res.code === 200) {
        ElMessage.success("删除成功！")
        getList(queryParams);
      } else {
        ElMessage.warning("删除失败，本用户是管理员或删除的用户里包括管理员！");
      }
    }).catch(err => console.log(err))
  }).catch(() => {
    ElMessage.info("删除取消")
  })
}

let queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  // 登录名
  userName: null,
  // 昵称
  nickName: null,
  // 用户类型
  userType: null,
  // 用户状态是否停用
  status: null
})

// queryParams表单的引用
let queryForm = ref()

let form = reactive({
  // 用户id，bigint
  userId: null,
  // 登录名
  userName: null,
  // 昵称
  nickName: null,
  // 用户类型
  userType: null,
  // email
  email: null,
  // 电话号码
  phonenumber: null,
  // 性别，不做展示
  sex: null,
  password: null,
  status: null
})

// 列表数据
let tableData = ref([])
// 列表遮罩层
let tableLoading = ref(false)
// 本页面列表总数
let total = ref(0)
const handleQuery = () => {
  getList(queryParams);
}

// 重置queryQueryParams表单
const resetQuery = () => {
  if (!queryForm.value) {
    return;
  }
  queryForm.value.resetFields()
  queryParams.pageNum = 1;
  queryParams.pageSize = 10;
  handleQuery();
}

// 获取主体table数据
const getList = (query) => {
  tableLoading.value = true;
  queryAllSatisfiedUsers(query).then(res => {
    tableData.value = res.rows;
    // 对请求来的后台数据做清洗，改变枚举类型
    tableData.value.map(item => {
      switch (item.userType) {
        case '00':
          item.userType = '系统管理员';
          break;
        case '01':
          item.userType = '食堂管理员';
          break;
        case '10':
          item.userType = '教师';
          break;
        case '11':
          item.userType = '学生';
          break;
      }
      switch (item.sex) {
        case '0':
          item.sex = '男';
          break;
        case '1':
          item.sex = '女';
          break;
        case '2':
          item.sex = '未知';
          break;
      }
      item.status = item.status === '1' ? '停用' : '正常';
    })
    total.value = parseInt(res.total);
    tableLoading.value = false;
  })
}

let avatarContent = reactive({
  fileContent: null
})

const resetAvatarContent = () => {
  avatarContent.fileContent = null
}

// 记录当前路由
let currentUrl = ref()

// 记录当前登录用户昵称
let nickname = ref(getLocalStorage(KEY_NICKNAME))

// 记录当前用户登陆的食堂id
// let restaurantId = getLocalStorage(KEY_RESTAURANT_ID);

// 记录当前登录用户头像，后期应该要大改
let avatarSrc = baseStaticRecourseAPI[NOW_ENVIRONMENT] + getLocalStorage(KEY_AVATAR)

onBeforeMount(() => {
  getList(queryParams);
})

onMounted(() => {
  // ;
  // console.log(currentUrl);
  // console.log(route)
})
</script>

<style scoped>
.is-active {
  color: #f9f9f9 !important;
  background-color: #47739a;
  border-radius: 20px;
  margin: 0 10px;
}

.el-menu-item {
  margin: 5px 10px !important;
}

.el-menu-item:hover {
  border-radius: 20px;
}
</style>